var createError = require('http-errors'); // 导入http-errors，抛出http error
var express = require('express'); // 导入express
var path = require('path'); // 导入路径模块
var cookieParser = require('cookie-parser'); // 导入解析cookie模块
var logger = require('morgan'); // 导入日志模块
var bodyParser = require('body-parser'); // 模块加载一定要在router之前
var session = require('express-session');
const template = require('art-template'); // 导入art-template模板
var moment = require('moment');
const formidable = require('express-formidable')

var indexRouter = require('./routes/index');  // 路由
var { router: userRouter } = require('./routes/user');
var blog = require('./routes/blog');

var app = express();

// body-parser, parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));
// parse application/json
app.use(bodyParser.json());
// app.use(formidable())
// view engine setup
app.engine('html', require('express-art-template'));
app.set('views', path.join(__dirname, 'views'));  // 模板引擎
// app.set('view engine', 'html');

// 设置过滤器
template.defaults.imports.remove_blank_space = (str) => {
    return str.trim();
};

template.defaults.imports.dateFormat = function (date, format) {
    moment.locale('zh-cn');
    return moment(date).format(format);
};
template.defaults.imports.remove_quotes = (str) => {
    return str.replace(/"/g, '')
};
//————————————————————————————————

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const MongoStore = require('connect-mongo')

app.use(session({  // 处理session
    secret: 'ddf8834/+-d*/f8f4dsqe21ere55$dd26333998', // 加密
    store: MongoStore.create({
        mongoUrl: 'mongodb://localhost/blog',
    }),
    cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 14
    },
    resave: false,
    saveUninitialized: true
}));

app.use(function (req, res, next) { // 自定义中间件
    // res.locals是一个对象，包含用于渲染视图的上下文
    // 用来存储一些全局变量什么的，
    res.locals.session = req.session;
    next()
});

app.use('/', indexRouter);  // 路由注册
app.use('/user', userRouter); // 用户路由
app.use('/blog', blog); // 文章详情
// catch 404 and forward to error handler
app.use(function (req, res, next) { // 404 处理
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development // 本地环境，开发中提供错误
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    // res.send(res.locals);
    res.send(`<body><h1>${res.statusCode}</h1><div>${err.message}</div></body>`)
});

module.exports = app;
